
//MENU
var MenuJ2 = function(){

	this.J = '';

	//Initialisation
	this.init = function(j){
		this.J = j;
	};
	//Mise à jour
	this.update = function(){
		this.render();
	}

	//Affichage
	this.render = function(){
		ctx[this.J].fillStyle = "#88F";
		ctx[this.J].fillRect(0, 0, MAX_WIDTH_J2, MAX_HEIGHT_J2);
		ctx[this.J].fillStyle = "#000";
		var header = '[PRESS ENTER TO START]';
		ctx[this.J].fillText(header, (MAX_WIDTH_J2/2)-header.length*3, MAX_HEIGHT_J2/2);
	};
	//Gestion des inputs
	this.input = function(){
		if(getKey('enter').state){
			CurrentGameObject_J2 = gameJ2;
		}
	};
};
var menuJ2 = new MenuJ2();

// Map
var MapJ2 = function(){
	this.parentObj = null;
	// Liste des noeuds du réseau
	this.nodes = [];
	// Offset d'affichage de la barre QTE
	this.offset = 30;
	// Vitesse de déplacement	
	this.speed = 0;
	// Contexte d'affichage
	this.context = null;
	// Variables booléennes 
	// Est-ce qu'une QTE est lancée ? 
	// Est-ce qu'il faut vérifier les inputs pour la QTE ?
	// Est-ce que le J2 a échoué
	this.launchedQTE = false;
	this.goToCheckQTE = false;
	this.failed = false;
	// La liste des QTE à saisir
	this.qteToShow = [];
	// La liste des QTE saisies
	this.qteDisabled = [];
	// La QTE à saisir
	this.qteToPress = '';
	// Valeur d'attente des timers
	this.timeToWait = 0;
	// Timer QTE et Failed
	this.timerQTE = null;
	this.timerFailed = null;
	// Paramètres issu de l'objet CharacterJ2
	this.selectedNode = null;
	this.lastQTE = 0;
	// Background
	this.bg = new Image();
	this.bg.src = 'assets/DecorsP2_Detour.png';
	this.bg.x = 0;
	this.bg.y = 0;

	// Lignes de parcours
	this.lineOne = ((MAX_HEIGHT_J2-this.offset)/2)/2 + 60;
	this.lineTwo = ((MAX_HEIGHT_J2-this.offset)/2)/2 + ((MAX_HEIGHT_J2-this.offset)/2) + 10;

	// Initialisation de la MAP
	this.init = function(p) {
		this.parentObj = p;
		this.speed = GAME_SPEED;
		var tmpNode;
		var tmpY = 0;
		for (node in gameJ1.map.nodes) {
			gameJ1Node = gameJ1.map.nodes[node];
			if (gameJ1Node.tag == 'trap') {
				this.nodes.push(
					{
						ref: gameJ1Node,
						x: 0,
						y: 0,
						w: 47,
						h: 48,
						nodeLeft: null,
						nodeTop: null,
						nodeRight: null,
						nodeBottom: null,
						active: false,
						enabledByDefault: false,
						qteType: 'inline',
						qte: generateQTE(5)
					}
				);
				//this.nodes[(this.nodes.length)-1].x = gameJ1.map.nodes[node].bounds.x+gameJ1.map.nodes[node].bounds.w/2-this.nodes[this.nodes.length-1].w/2;
				//this.nodes[(this.nodes.length)-1].y = this.offset+gameJ1.map.nodes[node].bounds.y/2;
				
				this.nodes[(this.nodes.length)-1].x = gameJ1Node.bounds.x;

				tmpY = gameJ1Node.bounds.y;
				if (gameJ1Node.name == "lanceFlamme") tmpY += gameJ1Node.bounds.h/2;

				if (tmpY < 300) {
					this.nodes[(this.nodes.length)-1].y = this.lineOne;
				}
				else if (tmpY < 480) {
					this.nodes[(this.nodes.length)-1].y = this.lineTwo;
				}

				this.nodes[(this.nodes.length)-1].active = gameJ1.map.nodes[node].active;
				this.nodes[(this.nodes.length)-1].enabledByDefault = gameJ1.map.nodes[node].active;
			}
		}

		for (node in this.nodes) {
			if (this.nodes[parseInt(node)+1] != undefined) {
				nextNode = this.nodes[parseInt(node)+1];
				if (nextNode.y > this.nodes[node].y) {
					this.nodes[node].nodeBottom = nextNode;
				}
				else if (nextNode.y < this.nodes[node].y) {
					this.nodes[node].nodeTop = nextNode;
				}
				else if (nextNode.y == this.nodes[node].y) {
					this.nodes[node].nodeRight = nextNode;
				}
			}
			if (this.nodes[parseInt(node)-1] != undefined) {
				this.nodes[node].nodeLeft = this.nodes[parseInt(node)-1];	
			}
		}
	};

	// Fonction de display de la MAP
	this.render = function() {
		this.context = ctx[this.parentObj.J];
		this.context.fillStyle = "#000";
		this.context.fillRect(0, 0, MAX_WIDTH_J2, MAX_HEIGHT_J2);
		gameJ2.character.render();

		for (node in this.nodes) {
			var node = this.nodes[node];
			var nextNode = null;

			if (node.nodeLeft != null) nextNode = node.nodeLeft;
			else if (node.nodeTop != null) nextNode = node.nodeTop;
			else if (node.nodeRight != null) nextNode = node.nodeRight;
			else if (node.nodeBottom != null) nextNode = node.nodeBottom;
			if (nextNode != null) {
				if (!this.failed) {
					this.context.strokeStyle = "#95E699";
				}
				else {
					this.context.strokeStyle = "#FF0E00";
				}
				this.context.beginPath();
				this.context.moveTo(node.x+node.w/2,node.y+node.h/2+10);
				this.context.lineTo(nextNode.x+nextNode.w/2,nextNode.y+nextNode.h/2+10);
				this.context.closePath();
				this.context.stroke();
			}			
		}
		// Node display
		for (node in this.nodes) {
			var nodeImage = new Image();
			var stateImage = new Image();
			var node = this.nodes[node];
			
			if (node.active && !this.failed) stateImage.src = 'assets/NoeudActif.png';
			else stateImage.src = 'assets/NoeudInactif.png';

			if (!this.failed) { nodeImage.src = 'assets/iconeLaser.png'; }
			else {
				nodeImage.src = 'assets/iconeLaser2.png';
				stateImage.src = 'assets/NoeudInactif.png';
			}
			this.context.drawImage(stateImage, node.x-5, node.y + 22, 48, 48);
			this.context.drawImage(nodeImage, node.x, node.y, 47, 48);
			
		}
		this.context.fillStyle = "#FFF";
		this.context.drawImage(this.bg, 0, 0, MAX_WIDTH_J2, MAX_HEIGHT_J2);

		if (this.launchedQTE) {
			var qteToDisplay;
			var offset = 0;
			for (var iQ = 0; iQ < this.qteToShow.length ; iQ++) {
				qteToDisplay = new Image();
				qteToDisplay.src = this.qteToShow[iQ].src;
				if (this.qteToShow[iQ].state == true) {
					this.context.drawImage(qteToDisplay, 0, 0, 48, 48, 154+offset, 35, 48, 48);						
				}
				else { this.context.drawImage(qteToDisplay, 0, 48, 48, 48, 154+offset, 35, 48, 48); }
				offset += 50;
			}
		}
	
	};

	this.update = function() {
		this.move();
		this.render();
		if (this.goToCheckQTE) { this.checkQTE(); }
	};

	this.move = function(){
		var ip = 0;
		while(ip < this.nodes.length){
			var p = this.nodes[ip];
			p.x -= this.speed;
			++ip;
		}
	}

	this.launchQTE = function() {
		this.qteToShow = [];
		this.launchedQTE = true;
		var qte = this.selectedNode.qte;
		switch (this.selectedNode.qteType) {
			case 'inline'	:  	for (i = 0; i < qte.length; i++) {
									this.qteToShow.push(qte[i]);
								}
								this.timeToWait = 2000;
								break;
			case 'oneShot' : 	if (this.lastQTE < qte.length) this.qteToShow.push(qte[this.lastQTE]);
								this.timeToWait = 2000;
								break;
		}

		this.convertQTE(this.qteToShow,this.lastQTE);


		if (this.lastQTE < qte.length) {
			this.qteToPress = qte[this.lastQTE];
			this.goToCheckQTE = true;
		}
		else {
			this.goToCheckQTE = false;
			this.launchedQTE = false;
			var oldNodeStateJ1 = this.selectedNode.ref.active;
			var oldNodeStateJ2 = this.selectedNode.active;
			this.setAllNodesToActive();
			this.selectedNode.ref.active = !oldNodeStateJ1;
			this.selectedNode.active = !oldNodeStateJ2;

			gameJ2.multiplicateur++;
			if (gameJ2.multiplicateurTimer != null) {
				clearTimeout(gameJ2.multiplicateurTimer);
			}
			gameJ2.multiplicateurTimer = setTimeout("resetMultiplicateur();",6000);
		}
	}

	this.convertQTE = function(qteToDo,lastQTE) {
		var assets = [];
		for (ik=0;ik<qteToDo.length;ik++) {
			switch (qteToDo[ik]) {
				case 'triangle' : 	assets.push({src:'assets/Triangle.png',state: (ik >= lastQTE)});
									break;
				case 'circle' : 	assets.push({src:'assets/Rond.png',state: (ik >= lastQTE)});
									break;
				case 'cross' : 		assets.push({src:'assets/Croix.png',state: (ik >= lastQTE)});
									break;
				case 'square': 		assets.push({src:'assets/Carre.png',state: (ik >= lastQTE)});
									break;
			}
		}
		this.qteToShow = assets;
	}

	this.checkQTE = function() {
		if (this.timerQTE == null) {
			this.timerQTE = setTimeout("setFailed();",this.timeToWait); 
		}
		if( !getKey(this.qteToPress).state && getKey(this.qteToPress).trigger ) {
			getKey(this.qteToPress).trigger = 0;
			this.qteDisabled.push(this.qteToPress);
			this.lastQTE++;
			clearTimeout(this.timerQTE);
			this.timerQTE = null;

			var len = this.selectedNode.qte.length;
			var p   = this.selectedNode.ref;

			if(p.animate){
				nbImg = ((p.sprite.bgw /2 / len / p.sprite.w) | 0) + 1;
				
				p.render(nbImg);
			}

			this.launchQTE();
			KEYPRESS = null;
		}
		else if (KEYPRESS != this.qteToPress && (KEYPRESS == 'triangle' || KEYPRESS == 'circle' || KEYPRESS == 'cross' || KEYPRESS == 'square')) {
			setFailed();
			KEYPRESS = null;
		}
		if (this.failed) {
			clearTimeout(this.timerQTE);
			this.goToCheckQTE = false;
			this.launchedQTE = false;
			this.qteToShow = [];
			this.lastQTE = 0;

			if (this.timerFailed == null) {
				this.timerFailed = setTimeout("setFailed();",2000);
			}
		}
	}

	this.setAllNodesToActive = function() {
		for (node in this.nodes) {
			if (this.nodes[node].enabledByDefault) { 
				this.nodes[node].active = true;
				this.nodes[node].ref.active = true;
			}
		}
	}
};

var GameJ2 = function(){
	this.J = '';
	this.map = null;
	this.character = null;
	this.multiplicateur = 1;
	this.multiplicateurTimer = null;

	//Initialisation
	this.init = function(j){
		this.J = j;
		this.map = new MapJ2();		
		this.character = new CharacterJ2();			

		this.map.init(this);
		this.character.init(this.J,this.map);
	};
	//Mise à jour
	this.update = function(){
		this.render();
		this.map.update();
		this.character.update();
	};

	//Affichage
	this.render = function(){		
	};
	
	//Gestion des inputs
	this.input = function(){
	
	};
};
var gameJ2 = new GameJ2();

/**
 * CHARACTER J2
 **/
var CharacterJ2 = function() {
 	this.J = '';
 	this.map = null;
 	this.speed = 0;
 	this.spritesImg = [{
	 	img : 'assets/Joueur.png',
	 	x   : 0,
	 	y   : 0,
	 	w   : 96,
	 	h   : 48,
	 	bgx : 0,
	 	bgy : 0,
	 	bgw : 96,	// WIDTH DU CHARACTER
	 	bgh : 48,	// HEIGHT DU CHARACTER
	 	k   : 0,
	 	currentNode : null
	}];
 	this.spritesRes = [];
 	this.lastQTE = 0;
 	
 	// Initialisation
	this.init = function(j,m) {
		this.J = j;
		this.map = m;
		this.speed = GAME_SPEED;
		for (i = 0; i < this.spritesImg.length; i++) {
			if(this.map.nodes.length > 0){
				this.spritesImg[i].x = this.map.nodes[0].x-28;
				this.spritesImg[i].y = this.map.nodes[0].y+22;
				this.spritesImg[i].currentNode = this.map.nodes[0];
			}
		}
	
		this.loadSprites();
	};

 	// Chargement des sprites du character
 	this.loadSprites = function() {
 		var is = 0;
 		while( is < this.spritesImg.length ) {
 			var img = new Image();
 			img.src = this.spritesImg[is].img;
 			this.spritesRes.push( img );
 			is++;
 		}
 	};

 	// Update des coordonnées du character @ each frame
 	this.update = function() {
 		if (!this.map.failed && !this.map.launchedQTE) { this.input(); }
 		this.move();
 		//this.render();
 		gameJ2.map.render();
 	};

 	// Affichage à l'écran du character
 	this.render = function() {
 		var ic = 0;
 		var r1 = new Image();
 		r1.src = 'assets/PressR1.png';
		while( ic < this.spritesRes.length ) {
			var img = this.spritesRes[ic];
			var s = this.spritesImg[ic];

			ctx[this.J].drawImage( img,
				s.bgx, // position x en image source
				s.bgy, // position y en image source
				s.bgw, // largeur image source
				s.bgh, // hauteur image source
				s.x, // position X sur canvas de destination
				s.y, // position Y sur canvas de destination
				s.bgw, // largeur Y sur canvas de destination (possibilité de zoom)
				s.bgh // hauteur Y sur canvas de destination (possibilité de zoom)
			);
			++ic;
		}

		if (!this.failed) { ctx[this.J].drawImage(r1, s.currentNode.x+40,s.currentNode.y-20,49,48); }
 	};

	this.move = function(){
		var ia = 0;
		while(ia < this.spritesImg.length){
			var s = this.spritesImg[ia];
			if ((s.x - this.speed) > 0) {
				s.x -= this.speed;
			}
			else {
				if (!this.map.launchedQTE) {
					if(s.currentNode){
						if (s.currentNode.nodeRight != null) {
							var targetNode = s.currentNode.nodeRight;
							//moveOblique(s.currentNode.x,s.currentNode.y,targetNode.x,targetNode.y,this);
							s.x = targetNode.x+targetNode.w/2-s.bgw/2;
							s.y = targetNode.y+targetNode.h/2-s.bgh/2+22;
							s.currentNode = targetNode;		
						}
						else {
							s.x -= this.speed;
						}
					}
				}
				else {
					s.x -= this.speed;
				}
			}
			++ia;
		}
	}
	
 	this.input = function(){
 		// Permet d'écouter également les inputs de cette classe dans le run() parent
 		//this.input
 		
		var ia = 0;
		while(ia < this.spritesImg.length ) {
			var s = this.spritesImg[ia];
			var targetNode = null;

			
			if( !getKey('z').state && getKey('z').trigger ) {
				if (s.currentNode.nodeTop != undefined) {
					targetNode = s.currentNode.nodeTop;
					getKey('z').trigger = 0;
				}
			}
			if( !getKey('d').state && getKey('d').trigger ) {
				if (s.currentNode.nodeRight != undefined) {
					targetNode = s.currentNode.nodeRight;
					getKey('d').trigger = 0;
				}
			}
			if( !getKey('s').state && getKey('s').trigger ) {
				if (s.currentNode.nodeBottom != undefined) {
					targetNode = s.currentNode.nodeBottom;
					getKey('s').trigger = 0;
				}
			}
			if( !getKey('q').state && getKey('q').trigger ) {
				if (s.currentNode.nodeLeft != undefined) {
					targetNode = s.currentNode.nodeLeft;
					getKey('q').trigger = 0;
				}
			}
			if( !getKey('space').state && getKey('space').trigger ) {
				this.map.selectedNode = s.currentNode;
				this.map.lastQTE = this.lastQTE;
				this.map.launchQTE();
				getKey('space').trigger = 0;
			}

			if (targetNode != undefined) {
				if (targetNode.x > 0) {
					//moveOblique(s.currentNode.x,s.currentNode.y,targetNode.x,targetNode.y,this);
					s.x = targetNode.x+targetNode.w/2-s.bgw/2;
					s.y = targetNode.y+targetNode.h/2-s.bgh/2+22;
					s.currentNode = targetNode;	
				}						
			}
			ia++;
		}
 	}
};

function generateQTE(nbInput) {
	var listKey = ['cross','triangle','square','circle'];
	var listQTE = [];
	var random = null;
	var lastRandom = listKey.length;
	for (var i = 0; i < nbInput; i++) {
		do {
			random = listKey[randomXToY(0,listKey.length-1)];
		} while (random == lastRandom)
		lastRandom = random;
		listQTE.push(random);
	}
	return listQTE;
}

function randomXToY(minVal,maxVal,floatVal) {
  var randVal = minVal+(Math.random()*(maxVal-minVal));
  return typeof floatVal=='undefined'?Math.round(randVal):randVal.toFixed(floatVal);
}

function moveOblique(xStart,yStart,xStop,yStop,character) {
	var a = yStop-yStart;
	var b = -1*(xStop-xStart);
	var c = (yStart*xStop)-(xStart*yStop);
	var currentX = 0;
	do {
		currentX++;
		if (xStop > xStart ) character.spritesImg[0].x = xStart + currentX;
		else if (xStart > xStop) character.spritesImg[0].x = xStart - currentX;
		character.spritesImg[0].y = (a/(-b))*character.spritesImg[0].x + (c/-b);
	} while (currentX < Math.abs(xStop-xStart))
}

function setFailed() {
	gameJ2.map.failed = !gameJ2.map.failed;
	gameJ2.map.timerFailed = null;
}

function resetMultiplicateur() {
	gameJ2.multiplicateur = 1;
	clearTimeout(gameJ2.multiplicateurTimer);
	gameJ2.multiplicateurTimer = null;
}